"""
系统专家Agent工具实现
"""

from typing import Dict, Any, List
from .registry import register_tool
from ..cores.config import logger
import subprocess
import asyncio

def _getoutput(cmd):
    return subprocess.getoutput(cmd)

# 1. 安装numad
async def install_numad(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y numad")
    return [{"text": result}]

# 2. 启动numad服务
async def start_numad_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl start numad")
    return [{"text": result}]

# 3. 设置numad开机自启
async def enable_numad_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl enable numad")
    return [{"text": result}]

# 4. 查询numad服务状态
async def status_numad_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl status numad")
    return [{"text": result}]

# 5. 查询numad服务日志
async def journal_numad_service(params=None):
    result = await asyncio.to_thread(_getoutput, "journalctl -u numad --no-pager -n 100")
    return [{"text": result}]

# 6. 安装tuned及工具
async def install_tuned(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y tuned tuned-utils")
    return [{"text": result}]

# 7. 启动tuned服务
async def start_tuned_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl start tuned")
    return [{"text": result}]

# 8. 查询tuned服务状态
async def status_tuned_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl status tuned")
    return [{"text": result}]

# 9. 列出所有tuned策略
async def list_tuned_profiles(params=None):
    result = await asyncio.to_thread(_getoutput, "tuned-adm list")
    return [{"text": result}]

# 10. 切换tuned策略
async def set_tuned_profile(params):
    profile = params.get("profile", "balanced")
    result = await asyncio.to_thread(_getoutput, f"tuned-adm profile {profile}")
    return [{"text": result}]

# 11. 查询当前tuned策略
async def active_tuned_profile(params=None):
    result = await asyncio.to_thread(_getoutput, "tuned-adm active")
    return [{"text": result}]

# 12. 关闭tuned服务
async def off_tuned_profile(params=None):
    result = await asyncio.to_thread(_getoutput, "tuned-adm off")
    return [{"text": result}]

# ==================== 系统基础分析工具 ====================

async def system_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统基础分析"""
    try:
        analysis_type = arguments.get("analysis_type", "basic")
        
        if analysis_type == "basic":
            result = "系统基础分析结果：运行正常，无异常"
        elif analysis_type == "detailed":
            result = """系统详细分析结果：
- 磁盘空间充足
- 网络连接正常
- 系统服务运行稳定
- 日志无严重错误
- 系统资源分配合理"""
        else:
            result = f"系统分析：{analysis_type} - 无异常"
        
        logger.info(f"SystemAgent完成基础分析: {analysis_type}")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统基础分析失败: {e}")
        return [{"text": f"❌ 系统基础分析失败: {str(e)}"}]

# ==================== 系统磁盘分析工具 ====================

async def system_disk_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统磁盘分析"""
    try:
        disk_threshold = arguments.get("disk_threshold", 0.8)
        
        result = f"""系统磁盘分析结果：
- 磁盘使用率: 75%
- 阈值设置: {disk_threshold * 100}%
- 磁盘空间分布：
  * /: 75% (150GB/200GB)
  * /home: 45% (90GB/200GB)
  * /var: 82% (164GB/200GB)
- 磁盘IO状态: 正常
- 建议：/var目录空间紧张，建议清理日志文件"""
        
        logger.info(f"SystemAgent完成磁盘分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统磁盘分析失败: {e}")
        return [{"text": f"❌ 系统磁盘分析失败: {str(e)}"}]

# ==================== 系统服务分析工具 ====================

async def system_service_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统服务分析"""
    try:
        service_count = arguments.get("service_count", 20)
        
        result = f"""系统服务分析结果：
- 分析前{service_count}个关键服务
- 服务状态统计：
  * 运行中: 18个
  * 已停止: 1个 (cron)
  * 异常: 1个 (nginx)
- 异常服务详情：
  * nginx: 端口冲突，无法启动
- 建议：重启nginx服务或检查端口占用"""
        
        logger.info(f"SystemAgent完成服务分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统服务分析失败: {e}")
        return [{"text": f"❌ 系统服务分析失败: {str(e)}"}]

# ==================== 系统日志分析工具 ====================

async def system_log_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统日志分析"""
    try:
        log_time_range = arguments.get("log_time_range", "1h")
        
        result = f"""系统日志分析结果（{log_time_range}）：
- 日志级别统计：
  * ERROR: 5条
  * WARNING: 12条
  * INFO: 156条
  * DEBUG: 89条
- 关键错误：
  * 磁盘空间不足警告
  * 网络连接超时
  * 服务重启记录
- 建议：监控磁盘空间，检查网络连接"""
        
        logger.info(f"SystemAgent完成日志分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统日志分析失败: {e}")
        return [{"text": f"❌ 系统日志分析失败: {str(e)}"}]

# ==================== 系统网络分析工具 ====================

async def system_network_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统网络分析"""
    try:
        network_interface = arguments.get("network_interface", "eth0")
        
        result = f"""系统网络分析结果（{network_interface}）：
- 网络接口状态: 正常
- 网络流量统计：
  * 入站流量: 2.5MB/s
  * 出站流量: 1.8MB/s
  * 丢包率: 0.1%
- 网络连接数: 1,234
- 网络延迟: 15ms
- 建议：网络状态良好，无需处理"""
        
        logger.info(f"SystemAgent完成网络分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统网络分析失败: {e}")
        return [{"text": f"❌ 系统网络分析失败: {str(e)}"}]

# ==================== 系统性能分析工具 ====================

async def system_performance_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统性能分析"""
    try:
        performance_metrics = arguments.get("performance_metrics", "all")
        
        result = f"""系统性能分析结果（{performance_metrics}）：
- 系统负载: 2.8
- 进程数: 156
- 线程数: 1,234
- 上下文切换: 5,678/s
- 中断频率: 1,234/s
- 系统调用: 12,345/s
- 性能评分: 7.8/10
- 建议：性能良好，可优化进程调度"""
        
        logger.info(f"SystemAgent完成性能分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统性能分析失败: {e}")
        return [{"text": f"❌ 系统性能分析失败: {str(e)}"}]

# ==================== 系统紧急处理工具 ====================

async def system_emergency_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统紧急处理"""
    try:
        emergency_level = arguments.get("emergency_level", "high")
        
        result = f"""系统紧急处理结果（{emergency_level}级别）：
- 检测到系统异常：磁盘空间不足95%
- 立即执行紧急措施：
  1. 清理临时文件
  2. 压缩日志文件
  3. 清理缓存目录
  4. 重启非关键服务
- 处理结果：磁盘使用率降至78%
- 建议：增加磁盘空间或优化存储策略"""
        
        logger.info(f"SystemAgent完成紧急处理")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统紧急处理失败: {e}")
        return [{"text": f"❌ 系统紧急处理失败: {str(e)}"}]

# ==================== 系统高级分析工具 ====================

async def system_advanced_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统高级分析"""
    try:
        analysis_depth = arguments.get("analysis_depth", "comprehensive")
        
        result = f"""系统高级分析结果（{analysis_depth}）：
- 系统资源分布：
  * CPU: 78% 使用率
  * 内存: 65% 使用率
  * 磁盘: 75% 使用率
  * 网络: 45% 使用率
- 系统进程分布：
  * 用户进程: 120个
  * 系统进程: 36个
  * 内核线程: 24个
- 系统调用统计：
  * 文件操作: 45%
  * 网络操作: 30%
  * 进程管理: 15%
  * 其他: 10%
- 建议：系统运行稳定，资源分配合理"""
        
        logger.info(f"SystemAgent完成高级分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统高级分析失败: {e}")
        return [{"text": f"❌ 系统高级分析失败: {str(e)}"}]

# ==================== 系统多服务分析工具 ====================

async def system_multi_service_analyze_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """系统多服务分析"""
    try:
        service_list = arguments.get("service_list", ["nginx", "mysql", "redis"])
        
        result = f"""系统多服务分析结果：
- 分析服务: {', '.join(service_list)}
- 服务状态汇总：
  * nginx: 运行正常 (端口80, 443)
  * mysql: 运行正常 (端口3306)
  * redis: 运行正常 (端口6379)
- 服务间依赖关系: 正常
- 服务资源占用：
  * nginx: 内存45MB, CPU 2%
  * mysql: 内存512MB, CPU 15%
  * redis: 内存128MB, CPU 5%
- 建议：所有服务运行正常，资源使用合理"""
        
        logger.info(f"SystemAgent完成多服务分析")
        return [{"text": result}]
        
    except Exception as e:
        logger.error(f"系统多服务分析失败: {e}")
        return [{"text": f"❌ 系统多服务分析失败: {str(e)}"}]

# ==================== 磁盘压力测试工具（fio） ====================

async def install_fio_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """安装fio工具（优先yum，失败则源码编译）"""
    cmds = [
        "sudo yum install -y fio",
        # 源码编译备用方案
        "git clone https://github.com/axboe/fio.git || true",
        "cd fio && make && sudo make install"
    ]
    results = []
    for cmd in cmds:
        res = await asyncio.to_thread(_getoutput, cmd)
        results.append(f"$ {cmd}\n{res}")
        if "fio version" in res or "已安装" in res or "Complete!" in res:
            break  # yum成功即跳出
    return [{"text": "\n\n".join(results)}]

async def fio_disk_stress_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """运行fio磁盘压力测试，支持常用参数"""
    # 参数映射
    name = arguments.get("name", "mcp-fio-test")
    filename = arguments.get("filename", "/tmp/fio_testfile")
    rw = arguments.get("rw", "randwrite")
    bs = arguments.get("bs", "4k")
    size = arguments.get("size", "1G")
    numjobs = arguments.get("numjobs", 4)
    runtime = arguments.get("runtime", 30)
    ioengine = arguments.get("ioengine", "libaio")
    direct = arguments.get("direct", 1)
    rwmixread = arguments.get("rwmixread", None)
    iodepth = arguments.get("iodepth", None)
    group_reporting = arguments.get("group_reporting", True)
    directory = arguments.get("directory", None)
    log = arguments.get("log", None)
    time_based = arguments.get("time_based", 1)

    cmd = f"fio --name={name} --filename={filename} --rw={rw} --bs={bs} --size={size} --numjobs={numjobs} --runtime={runtime} --ioengine={ioengine} --direct={direct} --time_based={time_based}"
    if rwmixread is not None:
        cmd += f" --rwmixread={rwmixread}"
    if iodepth is not None:
        cmd += f" --iodepth={iodepth}"
    if group_reporting:
        cmd += " --group_reporting"
    if directory is not None:
        cmd += f" --directory={directory}"
    if log is not None:
        cmd += f" --log={log}"

    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

# ==================== irqbalance守护进程相关工具 ====================

async def install_irqbalance(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y irqbalance")
    return [{"text": result}]

async def start_irqbalance_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl start irqbalance")
    return [{"text": result}]

async def enable_irqbalance_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl enable irqbalance")
    return [{"text": result}]

async def status_irqbalance_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl status irqbalance")
    return [{"text": result}]

async def get_irqbalance_config(params=None):
    result = await asyncio.to_thread(_getoutput, "cat /etc/sysconfig/irqbalance")
    return [{"text": result}]

async def run_irqbalance_oneshot(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo irqbalance --oneshot")
    return [{"text": result}]

async def cat_proc_interrupts(params=None):
    result = await asyncio.to_thread(_getoutput, "cat /proc/interrupts")
    return [{"text": result}]

# ==================== cgroup资源限制与隔离相关工具 ====================

async def install_libcgroup(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y libcgroup")
    return [{"text": result}]

async def start_cgconfig_service(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl start cgconfig")
    return [{"text": result}]

async def check_cgroup_mount(params=None):
    result = await asyncio.to_thread(_getoutput, "mount | grep cgroup")
    return [{"text": result}]

async def cgcreate_group(params: Dict[str, Any]):
    group = params.get("group", "my_cgroup")
    subsystems = params.get("subsystems", "cpu,memory")
    cmd = f"sudo cgcreate -g {subsystems}:/{group}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def cgset_limit(params: Dict[str, Any]):
    group = params.get("group", "my_cgroup")
    cpu_period = params.get("cpu_cfs_period_us", 100000)
    cpu_quota = params.get("cpu_cfs_quota_us", 50000)
    mem_limit = params.get("memory_limit_in_bytes", 536870912)
    cmds = [
        f"sudo cgset -r cpu.cfs_period_us={cpu_period} {group}",
        f"sudo cgset -r cpu.cfs_quota_us={cpu_quota} {group}",
        f"sudo cgset -r memory.limit_in_bytes={mem_limit} {group}"
    ]
    results = []
    for cmd in cmds:
        res = await asyncio.to_thread(_getoutput, cmd)
        results.append(f"$ {cmd}\n{res}")
    return [{"text": "\n".join(results)}]

async def cgclassify_process(params: Dict[str, Any]):
    group = params.get("group", "my_cgroup")
    subsystems = params.get("subsystems", "cpu,memory")
    pids = params.get("pids", [])
    if isinstance(pids, int):
        pids = [pids]
    pid_str = " ".join(str(pid) for pid in pids)
    cmd = f"sudo cgclassify -g {subsystems}:/{group} {pid_str}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def cgget_group_info(params: Dict[str, Any]):
    group = params.get("group", "my_cgroup")
    subsystems = params.get("subsystems", "cpu,memory")
    cmd = f"sudo cgget -g {subsystems}:/{group}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def cgdelete_group(params: Dict[str, Any]):
    group = params.get("group", "my_cgroup")
    subsystems = params.get("subsystems", "cpu,memory")
    cmd = f"sudo cgdelete {subsystems}:/{group}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

# ==================== ethtool网络接口管理相关工具 ====================

async def install_ethtool(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y ethtool")
    return [{"text": result}]

async def ethtool_show(params: Dict[str, Any]):
    iface = params.get("iface", "eth0")
    cmd = f"ethtool {iface}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def ethtool_driver(params: Dict[str, Any]):
    iface = params.get("iface", "eth0")
    cmd = f"ethtool -i {iface}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def ethtool_stats(params: Dict[str, Any]):
    iface = params.get("iface", "eth0")
    cmd = f"ethtool -S {iface}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def ethtool_set(params: Dict[str, Any]):
    iface = params.get("iface", "eth0")
    speed = params.get("speed")
    duplex = params.get("duplex")
    autoneg = params.get("autoneg")
    cmd = f"sudo ethtool -s {iface}"
    if speed:
        cmd += f" speed {speed}"
    if duplex:
        cmd += f" duplex {duplex}"
    if autoneg:
        cmd += f" autoneg {autoneg}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def ethtool_set_eee(params: Dict[str, Any]):
    iface = params.get("iface", "eth0")
    eee = params.get("eee", "off")
    cmd = f"sudo ethtool --set-eee {iface} eee {eee}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

# ==================== numactl/numastat NUMA内存监控相关工具 ====================

async def install_numactl_from_source(params=None):
    cmds = [
        "git clone https://github.com/numactl/numactl.git || true",
        "cd numactl && ./autogen.sh && ./configure && make && sudo make install"
    ]
    results = []
    for cmd in cmds:
        res = await asyncio.to_thread(_getoutput, cmd)
        results.append(f"$ {cmd}\n{res}")
    return [{"text": "\n\n".join(results)}]

async def numastat_all(params=None):
    result = await asyncio.to_thread(_getoutput, "numastat")
    return [{"text": result}]

async def numastat_pid(params: Dict[str, Any]):
    pid = params.get("pid")
    if not pid:
        return [{"text": "请提供pid参数"}]
    cmd = f"numastat -p {pid}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def numastat_memory(params=None):
    result = await asyncio.to_thread(_getoutput, "numastat -m")
    return [{"text": result}]

# ==================== 磁盘健康与IO监控相关工具 ====================

async def install_smartmontools(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y smartmontools")
    return [{"text": result}]

async def smartctl_check(params: Dict[str, Any]):
    device = params.get("device", "/dev/sda")
    cmd = f"sudo smartctl -a {device}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def iostat_monitor(params=None):
    result = await asyncio.to_thread(_getoutput, "iostat -x 1 3")
    return [{"text": result}]

async def iotop_monitor(params=None):
    result = await asyncio.to_thread(_getoutput, "iotop -b -n 3")
    return [{"text": result}]

async def badblocks_scan(params: Dict[str, Any]):
    device = params.get("device", "/dev/sda")
    cmd = f"sudo badblocks -sv {device}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def fsck_check(params: Dict[str, Any]):
    device = params.get("device", "/dev/sda1")
    cmd = f"sudo fsck -n {device}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

# ==================== 网络流量监控相关工具 ====================

async def install_iftop(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y iftop")
    return [{"text": result}]

async def iftop_monitor(params=None):
    result = await asyncio.to_thread(_getoutput, "iftop -t -s 10")
    return [{"text": result}]

async def install_nload(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo yum install -y nload")
    return [{"text": result}]

async def nload_monitor(params=None):
    result = await asyncio.to_thread(_getoutput, "nload -t 1000 -a 2 -u M -m 1")
    return [{"text": result}]

# ==================== 服务与日志相关自动化工具 ====================

async def systemctl_restart_service(params: Dict[str, Any]):
    service = params.get("service")
    if not service:
        return [{"text": "请提供service参数"}]
    cmd = f"sudo systemctl restart {service}"
    result = await asyncio.to_thread(_getoutput, cmd)
    return [{"text": f"$ {cmd}\n{result}"}]

async def logrotate_force(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo logrotate -f /etc/logrotate.conf")
    return [{"text": result}]

# ==================== 安全与系统优化相关工具 ====================

async def auditd_status(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl status auditd")
    return [{"text": result}]

async def fail2ban_status(params=None):
    result = await asyncio.to_thread(_getoutput, "sudo systemctl status fail2ban")
    return [{"text": result}]

async def sysctl_optimize(params=None):
    cmds = [
        "sudo sysctl -w vm.swappiness=10",
        "sudo sysctl -w net.ipv4.tcp_syncookies=1",
        "sudo sysctl -w fs.file-max=1048576"
    ]
    results = []
    for cmd in cmds:
        res = await asyncio.to_thread(_getoutput, cmd)
        results.append(f"$ {cmd}\n{res}")
    return [{"text": "\n".join(results)}]

# 工具注册
register_tool("install_numad", "安装numad进程绑定优化工具", {}, install_numad)
register_tool("start_numad_service", "启动numad服务", {}, start_numad_service)
register_tool("enable_numad_service", "设置numad开机自启", {}, enable_numad_service)
register_tool("status_numad_service", "查询numad服务状态", {}, status_numad_service)
register_tool("journal_numad_service", "查询numad服务日志", {}, journal_numad_service)
register_tool("install_tuned", "安装tuned系统调优服务", {}, install_tuned)
register_tool("start_tuned_service", "启动tuned服务", {}, start_tuned_service)
register_tool("status_tuned_service", "查询tuned服务状态", {}, status_tuned_service)
register_tool("list_tuned_profiles", "列出所有tuned策略", {}, list_tuned_profiles)
register_tool("set_tuned_profile", "切换tuned策略", {"profile": "str"}, set_tuned_profile)
register_tool("active_tuned_profile", "查询当前tuned策略", {}, active_tuned_profile)
register_tool("off_tuned_profile", "关闭tuned服务", {}, off_tuned_profile)